package com.yuedou.api.util;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * @author by  zhouwei
 * @createtime 2017/12/14 14:45
 * @功能：
 */
public class ByteUtil {


    public static void main(String[] args) {
//        String s = "5";
//
//        s = String.format("%02s", s);
//        System.out.println(s);

        String ret = getIntByHex("2454")+"";
        System.out.println(ret);


        String receiveMsg = "01030C000009910000245400005B012F11";

        int dataLength = ByteUtil.getIntByHex(receiveMsg.substring(4, 6)) * 2;//  数据长度
//        Log.d(TAG + " parseSerialData 数据长度 : " , dataLength.toString());
        String cmd = receiveMsg.substring(2, 4);//  03命令
//        Log.d(TAG + " parseSerialData 命令编号 : " , cmd);
        String data = "";
        if(cmd.equals("03")){//上传测量结果  自动上传
            data = receiveMsg.substring(6, 6 + dataLength);
//            Log.d(TAG + "parseSerialData 总数据 : " , data);
            // 01 03 0C
            // 00 00 09 91    剂量率
            // 00 00 24 54    计数率
            // 00 00 5B 01    活度

            String dose = data.substring(0, 8);
            int doseRate = ByteUtil.getIntByHex(dose);
            System.out.println(" parseSerialData 剂量率 : " + doseRate);
            int doseLeft = ByteUtil.getIntByHex(dose.substring(0, 4));
            int doseRight = ByteUtil.getIntByHex(dose.substring(4, 8));

            double doseTotal = (doseLeft * 65536 + doseRight * 1) / 100;
            System.out.println(" parseSerialData 剂量率 结果: " + doseTotal);

            String counting = data.substring(8, 16);
            int countingRate = ByteUtil.getIntByHex(counting);
            System.out.println(" parseSerialData 计数率 : " + countingRate);
            int countingLeft = ByteUtil.getIntByHex(counting.substring(0, 4));
            int countingRight = ByteUtil.getIntByHex(counting.substring(4, 8));

            double countingTotal = countingLeft * 65536 + countingRight * 1;
            System.out.println(" parseSerialData 计数率 结果: " + countingTotal);


            String activity = data.substring(16, 24);
            int activityRate = ByteUtil.getIntByHex(activity);
            System.out.println(" parseSerialData 活度 : " + activityRate);
            int activityLeft = ByteUtil.getIntByHex(activity.substring(0, 4));
            int activityRight = ByteUtil.getIntByHex(activity.substring(4, 8));

            double activityTotal = (activityLeft * 65536 + activityRight * 1) / 1000;
            System.out.println(" parseSerialData 活度 结果: " + activityTotal);

        }


    }



    /**
     *  16进制转换成10进制
     * @param hex
     * @return
     */
    public static int getIntByHex(String hex){
        int decimal = Integer.parseInt(hex, 16);
//        System.out.println("数据： " + decimal);
        return decimal;
    }


    private final static char[] mChars = "0123456789ABCDEF".toCharArray();
    private final static String mHexStr = "0123456789ABCDEF";

    /**
     * 字符串转换成十六进制字符串
     * @param str String 待转换的ASCII字符串
     * @return String 每个Byte之间空格分隔，如: [61 6C 6B]
     */
    public static String str2HexStr(String str){
        StringBuilder sb = new StringBuilder();
        byte[] bs = str.getBytes();

        for (int i = 0; i < bs.length; i++){
            sb.append(mChars[(bs[i] & 0xFF) >> 4]);
            sb.append(mChars[bs[i] & 0x0F]);
//            sb.append(' ');
        }
        return sb.toString().trim();
    }


    /**
     * 10进制转16进制
     * @param num
     * @return
     */
    public static String int2Hex(int num){
        String hexNumber = Integer.toHexString(num);
//        System.out.println(hexNumber); // 输出 "ff"
        return hexNumber.toUpperCase();
    }


    /**
     * 把字符串 转换成byte[]
     * @param s
     * @return
     */
    public static byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] b = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            // 两位一组，表示一个字节,把这样表示的16进制字符串，还原成一个字节
            b[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16));
        }
        return b;
    }

    /**
     * byte[]数组转换为16进制的字符串
     *
     * @param bytes 要转换的字节数组
     * @return 转换后的结果
     */
    public static String bytesToHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(0xFF & bytes[i]);
            if (hex.length() == 1) {
                sb.append('0');
            }
            sb.append(hex);
        }
        return sb.toString();
    }


    /**
     *  字符串转Unicode再转16进制
     * @param str
     * @return
     */
    public static String str2UnicodeHex(String str){
//        String str = "第一行";// 这是你的字符串
        Charset charset = Charset.forName("GBK");
        byte[] bytes = str.getBytes(charset);
        return  ByteUtil.bytesToHexString(bytes).toUpperCase();
    }




    /**
     * 获取 22 号命令的 写命令的开关的 请求数据
     * @param weiIndex
     * @param intDataIndex
     * @param OpenOrClose
     * @return
     */
    public static String getHexData(int weiIndex, int intDataIndex,String OpenOrClose){
        String s = "";
//        开 01160000  FFFF  0001
//        关 01160000  FFFE  0000
        //0000 0000 0000 0000
        if(OpenOrClose.equals("0")){//关闭
            for(int i = 0; i < intDataIndex; i++){
                if(weiIndex - 1 == i){
                    s+="0";
                }else{
                    s+="1";
                }
            }
        }else{//开启
            for(int i = 0; i < intDataIndex; i++){
                if(weiIndex - 1 == i){
                    s+="1";
                }else{
                    s+="0";
                }
            }
        }
//        System.out.println("倒序之前："+s);
        s = StringUtil.daoxuStr(s);
//        System.out.println("倒序之后："+s);
        s = binaryString2hexString(s).toUpperCase();
        if(OpenOrClose.equals("0")){//关闭
            s = s + "0000";
        }else{
            s = "FFFF" + s;
        }
        return s;
    }

    /**
     * 把 二进制数据 转换成16进制  字符串
     * @param bString
     * @return
     */
    public static String binaryString2hexString(String bString){
        if (bString == null || bString.equals("") || bString.length() % 8 != 0)
            return null;
        StringBuffer tmp = new StringBuffer();
        int iTmp = 0;
        for (int i = 0; i < bString.length(); i += 4)
        {
            iTmp = 0;
            for (int j = 0; j < 4; j++)
            {
                iTmp += Integer.parseInt(bString.substring(i + j, i + j + 1)) << (4 - j - 1);
            }
            tmp.append(Integer.toHexString(iTmp));
        }
        return tmp.toString();
    }

    /**
     * 十六转二进制
     *
     * @param hex
     *            十六进制字符串
     * @return 二进制字符串
     */
    public static String hexStringToBinary(String hex) {
        hex = hex.toUpperCase();
        String result = "";
        int max = hex.length();
        for (int i = 0; i < max; i++) {
            char c = hex.charAt(i);
            switch (c) {
                case '0':
                    result += "0000";
                    break;
                case '1':
                    result += "0001";
                    break;
                case '2':
                    result += "0010";
                    break;
                case '3':
                    result += "0011";
                    break;
                case '4':
                    result += "0100";
                    break;
                case '5':
                    result += "0101";
                    break;
                case '6':
                    result += "0110";
                    break;
                case '7':
                    result += "0111";
                    break;
                case '8':
                    result += "1000";
                    break;
                case '9':
                    result += "1001";
                    break;
                case 'A':
                    result += "1010";
                    break;
                case 'B':
                    result += "1011";
                    break;
                case 'C':
                    result += "1100";
                    break;
                case 'D':
                    result += "1101";
                    break;
                case 'E':
                    result += "1110";
                    break;
                case 'F':
                    result += "1111";
                    break;
            }
        }
        return result;
    }
}
